<?php defined('BASEPATH') OR exit('No direct script access allowed.');

function nav_menu($args = array())
{
    $ci =& get_instance();
    $args = array_merge(array(
                             'group' => 'header',
                             'group_segment' => '',
                             'top' => false,
                             'separator' => '',
                             'link_class' => '',
                             'more_class' => '',
                             'class' => 'current',
                             'tag' => 'li',
                             'list_tag' => 'ul',
                             'indent' => '',
                             'return_arr' => false,
                             'items_only' => true
                        ), $args);
    extract($args);

    is_numeric($group_segment) ? $group = $ci->uri->segment($group_segment) : NULL;

    $ci->load->model(array('pages/pages_m', 'blog/blog_categories_m', 'navigation/navigation_m'));
    $links = $ci->pyrocache->model('navigation_m', 'get_link_tree', array($group), $ci->settings->navigation_cache);
    return _build_nav($links, $args);
}

function _build_nav($links = array(), $args = array())
{
    $is_current = false;
    $level = 0;

    $ci =& get_instance();

    $args = array_merge(array(
                             'group' => 'header',
                             'group_segment' => '',
                             'top' => false,
                             'separator' => '',
                             'link_class' => '',
                             'more_class' => '',
                             'current_class' => 'current',
                             'tag' => 'li',
                             'list_tag' => 'ul',
                             'indent' => '',
                             'echo' => false,
                             'return_arr' => false,
                             'items_only' => true
                        ), $args);
    extract($args);

    $output = $return_arr ? array() : '';
    $i = 1;
    $total = sizeof($links);

    if (!$return_arr) {
        switch ($indent)
        {
            case 't':
            case 'tab':
            case '	':
                $indent = "\t";
                break;
            case 's':
            case 'space':
            case ' ':
                $indent = "    ";
                break;
            default:
                $indent = FALSE;
                break;
        }

        if ($indent) {
            $ident_a = repeater($indent, $level);
            $ident_b = $ident_a . $indent;
            $ident_c = $ident_b . $indent;
        }
    }
    foreach ($links as $link)
    {
        $item = array();
        $wrapper = array();

        //         attributes of anchor
        $item['url'] = '';
        //         If its any other type than a URL, it needs some help becoming one
        //        var_dump($link['link_type']);
        switch ($link['link_type'])
        {
            case 'uri':
                $item['url'] = $link['uri'];
                break;

            case 'module':
                $item['url'] = $link['module_name'];
                break;

            case 'page':
                if ($page = $ci->pages_m->get_by(array_filter(array(
                                                                   'id' => $link['type_id'],
                                                                   'status' => (is_subclass_of(ci(), 'Public_Controller')
                                                                           ? 'live' : NULL)
                                                              )))
                ) {
                    $item['url'] = BASE_URL . $page->uri;
                    $link['is_home'] = $page->is_home;
                }
                else
                {
                    unset($links[$key]);
                }
                break;
            case 'cat':
                if ($cat = $ci->blog_categories_m->get_by(array_filter(array(
                                                                            'id' => $link['type_id']
                                                                       )))
                ) {
                    $item['url'] = 'blog/category/' . $cat->slug;
                }
                else
                {
                    unset($links[$key]);
                }
                break;
        }
        $item['title'] = $link['title'];
        $item['attributes']['target'] = $link['target'] ? 'target="' . $link['target'] . '"' : NULL;
        $item['attributes']['class'] = $link_class ? 'class="' . $link_class . '"' : '';

        // attributes of anchor wrapper
        $wrapper['class'] = $link['class'] ? explode(' ', $link['class']) : array();
        $wrapper['children'] = $return_arr ? array() : '';
        $wrapper['separator'] = $separator;

        // is single ?
        if ($total === 1) {
            $wrapper['class'][] = 'single';
        }

            // is first ?
        elseif ($i === 1)
        {
            $wrapper['class'][] = 'first';
        }

            // is last ?
        elseif ($i === $total)
        {
            $wrapper['class'][] = 'last';
            $wrapper['separator'] = '';
        }

        // has children ? build children
        if (!empty($link['children'])) {
            ++$level;
            $wrapper['class'][] = $more_class;
            $wrapper['children'] = _build_nav($link['children'], $args);
            --$level;
        }
        // is current ?
        if (current_url() === site_url($link['url']) OR ($link['link_type'] === 'page' && $link['is_home'] == 1) AND current_url() === BASE_URL) {
            $is_current = TRUE;
            $wrapper['class'][] = $current_class;
        }

        // has children as current ?
        if ($is_current) {
            if (!in_array($current_class, $wrapper['class'])) {
                $wrapper['class'][] = 'has_' . $current_class;
            }

            if ($level === 0) {
                // we've got the expected result, stop check if has current children
                $is_current = FALSE;
            }
        }

        ++$i;

        if ($return_arr) {
            $item['target'] =& $item['attributes']['target'];
            $item['class'] =& $item['attributes']['class'];
            $item['children'] = $wrapper['children'];

            if ($wrapper['class'] && $item['class']) {
                $item['class'] = implode(' ', $wrapper['class']) . ' ' . substr($item['class'], 7, -1);
            }
            elseif ($wrapper['class'])
            {
                $item['class'] = implode(' ', $wrapper['class']);
            }

            if ($item['target']) {
                $item['target'] = substr($item['target'], 8, -1);
            }

            // assign attributes to level family
            $output[] = $item;
        }
        else
        {
            //deprecated
            $add_first_tag = $level === 0 && !in_array($items_only, array('1', 'y', 'yes', 'true'));

            // render and indent or only render inline?
            if ($indent) {
                $output .= $add_first_tag ? "<{$list_tag}>" . PHP_EOL : '';
                $output .= $ident_b . '<' . $tag . ' class="' . implode(' ', $wrapper['class']) . '">' . PHP_EOL;
                $output .= $ident_c . ((($level == 0) AND $top == 'text' AND $wrapper['children']) ? $item['title']
                        : anchor($item['url'], $item['title'], trim(implode(' ', $item['attributes'])))) . PHP_EOL;

                if ($wrapper['children']) {
                    $output .= $ident_c . "<{$list_tag}>" . PHP_EOL;
                    $output .= $ident_c . $indent . str_replace(PHP_EOL, (PHP_EOL . $indent), trim($ident_c . $wrapper['children'])) . PHP_EOL;
                    $output .= $ident_c . "</{$list_tag}>" . PHP_EOL;
                }

                $output .= $wrapper['separator'] ? $ident_c . $wrapper['separator'] . PHP_EOL : '';
                $output .= $ident_b . "</{$tag}>" . PHP_EOL;
                $output .= $add_first_tag ? $ident_a . "</{$list_tag}>" . PHP_EOL : '';
            }
            else
            {
                $output .= $add_first_tag ? "<{$list_tag}>" : '';
                $output .= '<' . $tag . ' class="' . implode(' ', $wrapper['class']) . '">';
                $output .= (($level == 0) AND $top == 'text' AND $wrapper['children']) ? $item['title']
                        : anchor($item['url'], $item['title'], trim(implode(' ', $item['attributes'])));

                if (!empty($wrapper['children'])) {
                    $output .= "<{$list_tag}>";
                    $output .= $wrapper['children'];
                    $output .= "</{$list_tag}>";
                }

                $output .= $wrapper['separator'];
                $output .= "</{$tag}>";
                $output .= $add_first_tag ? "</{$list_tag}>" : '';
            }
        }
    }
    return $output;
}